//
// Created by Soar Qin on 2017/8/18.
// Copyright (c) 2017 Soar Qin. All rights reserved.
//

#include "common.hh"

#include "loop.hh"

#include "timer.hh"

#include "private/loop_private.hh"

#include <event2/thread.h>

namespace core::async {

bool Loop::initialized_ = []() {
#ifdef _WIN32
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
#if EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
    evthread_use_windows_threads();
#elif EVTHREAD_USE_PTHREADS_IMPLEMENTED
    evthread_use_pthreads();
#endif
    return true;
}();

Loop::Loop(): context_(new LoopContext) {
    auto *conf = event_config_new();
    event_config_set_flag(conf, EVENT_BASE_FLAG_STARTUP_IOCP | EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
    event_config_require_features(conf, EV_FEATURE_ET);
    context_->evbase = event_base_new_with_config(conf);
    if (context_->evbase == nullptr) {
        event_config_require_features(conf, 0);
        context_->evbase = event_base_new_with_config(conf);
    }
    event_config_free(conf);
    context_->httpMulti = nullptr;
    context_->httpTimer = nullptr;
    context_->data = nullptr;
}

Loop::~Loop() {
    delete context_;
}

void Loop::run() {
    event_base_loop(context_->evbase, 0);
}

}
